package com.koala.learn.threadlearn.charter1;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Date 2022/2/26 12:18
 * @Created by koala
 */
@AllArgsConstructor
@NoArgsConstructor
class DelayElements implements Delayed {

    private String key;

    // 存活时间
    private long aliveTime;
    // 过期时间
    private long timeOut;

    public long getTimeOut() {
        return timeOut;
    }

    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getAliveTime() {
        return aliveTime;
    }

    public void setAliveTime(long aliveTime) {
        this.aliveTime = aliveTime;
    }

    public DelayElements(String key, long aliveTime) {
        super();
        this.key = key;
        this.aliveTime = aliveTime;
        this.timeOut = TimeUnit.NANOSECONDS.convert(aliveTime, TimeUnit.SECONDS) + System.nanoTime();
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == null)
            return 1;
        if (o == this)
            return 0;
        if (o instanceof DelayElements) {
            DelayElements de = (DelayElements) o;
            if (this.timeOut > de.getTimeOut()) {
                return 1;
            } else if (this.timeOut < de.getTimeOut()) {
                return -1;
            }
        }
        return 0;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(timeOut - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DelayElements other = (DelayElements) obj;
        if (key == null) {
            return other.key == null;
        } else return key.equals(other.key);
    }


}